package com.youdianstar.app.common.network

import android.net.ParseException
import android.util.Log
import android.view.View
import androidx.lifecycle.Observer
import com.youdianstar.app.common.loadsir.EmptyCallback
import com.youdianstar.app.common.loadsir.ErrorCallback
import com.youdianstar.app.common.loadsir.LoadingCallback
import com.youdianstar.app.common.network.model.BaseResponse
import com.youdianstar.app.common.network.model.DataState
import com.google.gson.JsonParseException
import com.kingja.loadsir.callback.Callback
import com.kingja.loadsir.callback.SuccessCallback
import com.kingja.loadsir.core.Convertor
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.youdianstar.app.common.loadsir.EmptyInviteCallback
import org.json.JSONException
import retrofit2.HttpException
import java.io.InterruptedIOException
import java.net.ConnectException


/**
 * File: BaseApiStateObserver
 * Author: 82149 Create: 2021/9/18 14:55
 * Changes (from 2021/9/18)
 * --------------------------------------------------
 * description: 接口数据回调--更改UI(单页列表 or 子控件)
 * ---------------------------------------------------
 *
 */
private const val TAG = "BaseApiStateObserver"

abstract class BaseApiStateObserver<T>(view: View?,isInvite:Boolean = false) : Observer<BaseResponse<T>>, Callback.OnReloadListener {
    /*UI处理*/
    private var mLoadService: LoadService<Any>? = null

    init {
        //LoadSir 针对单个View 做注册
        if (view != null) {
            mLoadService = LoadSir.getDefault().register(view, this, object : Convertor<BaseResponse<T>> {
                    override fun map(t: BaseResponse<T>?): Class<out Callback> {
                        var resultCode: Class<out Callback> = SuccessCallback::class.java
                        when (t?.dataState) {
                            //数据刚开始请求，loading
                            DataState.STATE_CREATE, DataState.STATE_LOADING -> {
                                resultCode = LoadingCallback::class.java
                            }
                            //请求成功
                            DataState.STATE_SUCCESS -> resultCode = SuccessCallback::class.java
                            //数据为空
                            DataState.STATE_EMPTY -> {
                                if (isInvite)
                                    resultCode = EmptyInviteCallback::class.java
                                else{
                                    resultCode = EmptyCallback::class.java
                                }
                            }
                            DataState.STATE_FAILED, DataState.STATE_ERROR -> {
                                when (val error: Throwable? = t.error) {
                                    is HttpException -> {
                                        //网络错误
                                        Log.e(TAG, "----HttpException:" + error.message())
                                    }
                                    is ConnectException -> {
                                        //无网络连接
                                        Log.e(TAG, "----ConnectException:" + error.message)
                                    }
                                    is InterruptedIOException -> {
                                        //连接超时
                                        Log.e(TAG, "----InterruptedIOException:" + error.message)
                                    }
                                    is JsonParseException, is JSONException, is ParseException -> {
                                        //解析错误
                                        Log.e(TAG, "----JsonEx:" + error.message)
                                    }
                                    else -> {
                                        //未知错误
                                        Log.e(TAG, "----unknown:" + error?.message)
                                    }
                                }
                                resultCode = ErrorCallback::class.java
                            }
                            DataState.STATE_COMPLETED, DataState.STATE_UNKNOWN -> {
                                //非普通异常,默认给成功吧
                                resultCode = SuccessCallback::class.java
                            }
                            else -> {
                                resultCode = SuccessCallback::class.java
                            }
                        }
                        return resultCode
                    }
                })
        }
    }


    /*数据处理*/
    override fun onChanged(t: BaseResponse<T>) {
//        Log.d(TAG, "onChanged: ${t.dataState}")
        when (t.dataState) {
            DataState.STATE_SUCCESS -> {
                onDataResult(t.data)
            }

            DataState.STATE_EMPTY -> {
                onDataEmpty()
            }

            DataState.STATE_FAILED -> {
                //请求错误 (单页列表 or 子控件, HttpEx 和错误码一起处理)
                t.message?.let {
                    onNetError(t.code, it)
                }
            }

            DataState.STATE_ERROR -> {
                t.error?.let {
                    onNetError(-1, it.message)
                }
            }
            else -> {
            }
        }
        mLoadService?.showWithConvertor(t)
    }

    /**
     * 请求数据且数据不为空
     */
    open fun onDataResult(data: T?) {

    }

    /**
     * 请求成功，但数据为空
     */
    open fun onDataEmpty() {

    }

    /**
     * 请求错误
     */
    open fun onNetError(code: Int, e: String?) {

    }


}